
package code.codeworld.know.knowledge.service.impl;

import code.codeworld.know.knowledge.mapper.KnowMapper;
import code.codeworld.know.knowledge.model.Know;
import code.codeworld.know.knowledge.model.vo.KnowVo;
import code.codeworld.know.knowledge.service.KnowService;
import code.codeworld.common.kits.Exceptions;
import code.codeworld.common.kits.PageUtil;
import code.codeworld.common.kits.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * knowService接口实现类
 *
 * @author freecode
 * @date 2023/03/23 00:20
 **/
@Service
public class KnowServiceImpl implements KnowService {
    @Resource
    private KnowMapper knowMapper;

    @Override
    public Page<KnowVo> page(KnowVo knowVo) {
        Integer[] pageLimits = new Integer[]{knowVo.getPage(), knowVo.getLimit()};
        PageUtil.getPageLimits(pageLimits);
        knowVo.setPage(pageLimits[0]);
        knowVo.setLimit(pageLimits[1]);
        Page<KnowVo> page = new Page<KnowVo>();
        List<Sort.Order> orderList = new ArrayList<>();
        if (!StringUtils.isEmpty(knowVo.getPageOrders())) {
            String[] orders = knowVo.getPageOrders().split(";");
            for (String order : orders) {
                String[] item = order.split(",");
                orderList.add(new Sort.Order(item[0].equals("desc") ? Sort.Direction.DESC : Sort.Direction.ASC, item[1]));
            }
            knowVo.setSortField(orderList.get(0).getProperty());
            knowVo.setSortOrder(orderList.get(0).getDirection().name());
        }
        int count = knowMapper.findByKeywordCount(knowVo);
        if (count > BigDecimal.ROUND_UP) {
            List<KnowVo> data = knowMapper.findByKeyword(knowVo);
            //补充排序--sql执行多个字段排序时有时未生效后面的（数据limit、）
            if (orderList.size() > BigDecimal.ROUND_DOWN) {
                for (int i = 1; i < orderList.size(); i++) {
                    if (orderList.get(i).getProperty().equals("id")) {
                        if (orderList.get(i).isDescending()) {
                            data.stream().sorted(Comparator.comparing(Know::getId).reversed()).collect(Collectors.toList());
                        } else {
                            data.stream().sorted(Comparator.comparing(Know::getId)).collect(Collectors.toList());
                        }
                    }
                    if (orderList.get(i).getProperty().equals("starNum")) {
                        if (orderList.get(i).isDescending()) {
                            data.stream().sorted(Comparator.comparing(Know::getStarNum).reversed()).collect(Collectors.toList());
                        } else {
                            data.stream().sorted(Comparator.comparing(Know::getStarNum)).collect(Collectors.toList());
                        }
                    }
                }
            }
            int autoNum = pageLimits[0];
            for (KnowVo t : data) {
                //序号自增
                t.setAutoNum(++autoNum);
            }
            page.setRecords(data);
        }
        page.setTotal(count);
        return page;
    }

    @Override
    public List<KnowVo> list(KnowVo vo) {
        //分组查询
        if (!ObjectUtils.isEmpty(vo.getGroupFields())) {
            return knowMapper.findSomeGroupByKeyword(vo);
        }
        //部分查询
        return knowMapper.findSomeByKeyword(vo);
    }

    @Override
    public Result<String> editMark(Know know) {
        Know dbData = this.queryById(know.getId(), know.getType());
        if (know.getStarNum() != null) {
            dbData.setStarNum(dbData.getStarNum() + know.getStarNum());
        }
        if (know.getCollectNum() != null) {
            dbData.setCollectNum(dbData.getCollectNum() + know.getCollectNum());
        }
        if (!StringUtils.isEmpty(know.getComment())) {
            dbData.setComment(dbData.getComment() + "\\\\" + know.getComment());
        }
        int edit = knowMapper.upMarkOnId(dbData);
        if (edit < 1) {
            throw new Exceptions(Exceptions.ErrorCode.RUN_ERROR);
        }
        return Result.ok();
    }

    @Override
    public Know detail(Know know) {
        return this.queryById(know.getId(), know.getType());
    }

    @Override
    public Know queryById(Long id, String type) {
        return knowMapper.getById(id, type);
    }


}
